import Vue from 'vue'
import VueRouter from 'vue-router'

import HomePage from '../views/HomePage'


// 此VueRouter是自己自定义引入暴露出来的，即是自定义的，以下的VueRouter同样是这样
// 解决两次访问相同路由地址报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// () => import(/* webpackChunkName: "detail" */ '../views/DetailPage.vue'),
Vue.use(VueRouter)

const routes = [
    {
        path: "/",
        redirect: "/home"
    },
    {
        path: "/home",
        name: "home",
        component: HomePage,
        meta: {
            selected: "home"
        }
    },
    {
        path: "/type",
        name: "type",
        component: () => import(/* webpackChunkName: "detail" */ '../views/TypePage.vue'),
        meta: {
            selected: "type"
        }
    },
    {
        path: "/cart",
        name: "cart",
        component: () => import(/* webpackChunkName: "detail" */ '../views/CartPage.vue'),
        meta: {
            selected: "cart",
            hideTop: true,
            hideBottom: true,
            showFixedMenus: true,
            privately: true
        }
    },
    {
        path: "/about",
        name: "about",
        component: () => import(/* webpackChunkName: "detail" */ '../views/AboutPage.vue'),
        meta: {
            selected: "about",
            hideTop: true,
            privately: true
        }
    },
    {
        path: "/detail/:goodsId",
        name: "detail",
        component: () => import(/* webpackChunkName: "detail" */ '../views/DetailPage.vue'),
        meta: {
            hideTop: true,
            hideBottom: true,
            showFixedMenus: true
        }
    },
    {
        path: "/search",
        name: "search",
        component: () => import(/* webpackChunkName: "detail" */ '../views/SearchPage.vue'),
        meta: {
            hideBottom: true,
            showBack: true,
            showFixedMenus: true
        }
    },
    {
        path: "/login",
        name: "login",
        component: () => import(/* webpackChunkName: "detail" */ '../views/LoginPage.vue'),
        meta: {
            hideTop: true,
            hideBottom: true,
        }
    }
]

const router = new VueRouter({
    routes
})

router.beforeEach(function (to, from, next) {
    // console.log(to,from);
    // next();

    if (!to.meta.privately) {
        next();
        return;
    }

    let token = localStorage.getItem("token");
    //如果登录了就跳到about页面
    if (token) {
        next();
        //如果没登录就跳到login页面
    } else {
        window.$showTip("请先登录", 2);
        setTimeout(() => {
            next({
                name: "login",
                params: {
                    url: to.fullPath
                }
            });
        }, 1000);
    }
});

export default router
